/* 用户的增删改查 */
const   router = require('koa-router')(),
    DB = require('../../module/db.js'),
    tools = require("../../module/tools")

router.get('/',async(ctx) =>{
    var result = await DB.find('admin',{})
    // ctx.body = '用户首页'
    await ctx.render('admin/manage/list',{
        list:result
    })
})
router.get('/add',async(ctx) =>{
    // ctx.body = '用户首页'
    await ctx.render('admin/manage/add')
})
router.post('/doAdd',async(ctx) =>{
    // 获取表单数据
    //验证数据是否合法
    //数据库中管理员是否存在
    //增加管理员

    var username = ctx.request.body.username
    var password = ctx.request.body.password
    var rpassword = ctx.request.body.rpassword

    if(!/^\w{4,20}/.test(username)){
       await ctx.render('admin/error',{
            message:"用户名不合法",
            redirect: ctx.state.__HOST__+ '/admin/manage/add'
        })
    }else if(password != rpassword || password.length < 6){
        await ctx.render('admin/error',{
            message:"密码或确认密码不一致",
            redirect: ctx.state.__HOST__+ '/admin/manage/add'
        })
    }else{
        var findresult = await DB.find('admin',{'username':username})
        if(findresult.length > 0){
            await ctx.render('admin/error',{
                message:"此管理员已经存在",
                redirect: ctx.state.__HOST__+ '/admin/manage/add'
            })
        }else{
            //增加管理员
            var addresult = await DB.insert('admin',{'username':username,'password':tools.md5(password),'status':1,'last_time':''})
            await ctx.redirect(ctx.state.__HOST__+ '/admin/manage')
        }
    }

    
})
 router.get('/edit',async(ctx) =>{
   // ctx.body = '用户首页'
   var id = ctx.query.id
   var result  = await DB.find('admin',{'_id':DB.getObjectId(id)})
   await ctx.render('admin/manage/edit',{
       list:result[0]
   })
 
})

router.post('/doEidt',async(ctx) =>{
    try{
        var id = ctx.request.body.id
        var password = ctx.request.body.password
        var rpassword = ctx.request.body.rpassword
        if(password != ""){
            if(password != rpassword || password.length < 6){
                await ctx.render('admin/error',{
                    message:"密码或确认密码不一致",
                    redirect: ctx.state.__HOST__+ '/admin/manage/edit?id=' + id
                })
            }else{
                var updateResult = await DB.update('admin',{'_id':DB.getObjectId(id)},{"password":tools.md5(password)})
                ctx.redirect(ctx.state.__HOST__+ '/admin/manage')
            } 
        }else{
            ctx.redirect(ctx.state.__HOST__+ '/admin/manage')
        }
     
    }catch(err){
        await ctx.render('admin/error',{
            message:err,
            redirect: ctx.state.__HOST__+ '/admin/manage/edit?id=' + id
        })
    }
})
module.exports = router.routes()